package com.morgan.maxfinance;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.util.Calendar;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.util.Xml;

public class MainActivity extends Activity {
	
	public static final int STRING_TYPE = 0;
	public static final int INT_TYPE = 1;
	public static final int LONG_TYPE = 2;
	
	public static final String SETTING_FILE_NAME = "maxFinance.txt";
	public static final String SETTING_FILE_PATH = "/Android/data/com.morgan.maxfinance/files/";
	
//	public static final String APP_PATH = "/Android/data/com.example.maxfinance/files/";

	public static SharedPreferences sharedPreferences;
	long lMaxDiffTime;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		String strSubmitBefore;
		lMaxDiffTime = (long) ((long) (3600) * (long) (24) * (long) (1000) * (long) (30));

		sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//		saveInternalFileData();
//		readInternalFileData();
		
//		saveExternalFileData();
	    if (getIntent().getBooleanExtra("Exit me", false)) {
	        finish();
	        return; // add this to prevent from doing unnecessary stuffs
	    }
	   
//		String android_id = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
//		GlobalData.strDeviceID = android_id;
		
//    	new MyAsyncTask(MainActivity.this).execute("login");
    	
//		Log.e("Android","Android ID : " + android_id);
		
//		readExternalFileData();
		Log.e("strSubmit", sharedPreferences.getString("strSubmit", ""));
		Log.e("lastSubmissionTime", Long.toString(sharedPreferences.getLong("lastSubmissionTime", 0)));
		
		strSubmitBefore = sharedPreferences.getString("strSubmit", "");
		
        if (isNewInstall()) {
        	
        	NewIndexActivity.nType = NewIndexActivity.TYPE_NEW_APP;
        	startActivityForResult(new Intent(this, NewIndexActivity.class), 0);
        	
        } else {
        	
        	readExternalFileData();
        	String strSubmitResult = sharedPreferences.getString("strSubmitResult", "Pass");
        	
        	if (strSubmitResult.equals("Support Required")) {
        		
        		long lDiffTime = getTimeNowDiffLastSubmit();
        		if (lDiffTime > lMaxDiffTime) {
        			NewIndexActivity.nType = NewIndexActivity.TYPE_RE_LOAN;
        			startActivityForResult(new Intent(this, NewIndexActivity.class), 0);
        		} else {
        			// decline page
        			startActivityForResult(new Intent(this, DeclineActivity.class), 0);
        		}
        	}
        	if (strSubmitResult.equals("Pass")) {
        		
        		long lDiffTime = getTimeNowDiffLastSubmit();
        		if (lDiffTime > lMaxDiffTime) {
        			NewIndexActivity.nType = NewIndexActivity.TYPE_RE_LOAN;
        			startActivityForResult(new Intent(this, NewIndexActivity.class), 0);
        		} else {
        			// complete Page
        			startActivityForResult(new Intent(this, CompleteActivity.class), 0);
        		}
        	}
        }
	}
	
	public long getTimeNowDiffLastSubmit() {
		
		long lLastSubmitTime = sharedPreferences.getLong("lastSubmissionTime", 0);
		
		Calendar c = Calendar.getInstance();
		long lNowTime = c.getTimeInMillis();
		Log.e("HCW", Long.toString(lNowTime));
		
		long lDiffTime = lNowTime - lLastSubmitTime;
		
		return lDiffTime;
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    // Check which request we're responding to
	    finish();
	}
	
	private void saveInternalFileData() {
		String data = "han";
		try {
		    FileOutputStream fOut = openFileOutput("myData",MODE_WORLD_READABLE);
		    fOut.write(data.getBytes());
		    fOut.close();
		} catch (Exception e) {
		    // TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void readInternalFileData() {
		try{
			 FileInputStream fin = openFileInput("myData");
			 int c;
			 String temp="";
			 while( (c = fin.read()) != -1){
			    temp = temp + Character.toString((char) c);
			 }
			 
			 Log.e("Read Data", temp);
		} catch(Exception e) {

		}
	}
	
	public static void saveExternalFileData() {
		
		try {
			
		    File sdcard = new File(Environment.getExternalStorageDirectory() + SETTING_FILE_PATH);

	        if (!sdcard.exists())
	            sdcard.mkdirs();
	        
	        sdcard = new File(Environment.getExternalStorageDirectory() + SETTING_FILE_PATH);
	        File myFile = new File(sdcard, SETTING_FILE_NAME);

	        if (!myFile.exists()) {
	            try {
	            	myFile.createNewFile();
	            } catch (Exception e) {
	                // TODO: handle exception
	                e.printStackTrace();
	            }
	        }
	        
			FileOutputStream fOut = new FileOutputStream(myFile);
			OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
			
			appendToWriter(myOutWriter, "lastSubmissionTime", 	LONG_TYPE);
			appendToWriter(myOutWriter, "strSubmitResult", 		STRING_TYPE);
			appendToWriter(myOutWriter, "appID",				STRING_TYPE);
			
			myOutWriter.close();
			fOut.close();
		} catch (Exception e) {
			
		}
	}
	
	public static void appendToWriter(OutputStreamWriter writer, String tag, int type) {
		
		try {

			writer.append("<" + tag + ">");
			if (type == STRING_TYPE) {
				writer.append(sharedPreferences.getString(tag, ""));
			}
			if (type == INT_TYPE) {
				String str = Integer.toString(sharedPreferences.getInt(tag, 0));
				writer.append(str);
			}
			if (type == LONG_TYPE) {
				String str = Long.toString(sharedPreferences.getLong(tag, 0));
				writer.append(str);
			}
			
			writer.append("</" + tag + ">");
		} catch (Exception e) {
			
		}
	}
	
	public static void readExternalFileData() {
		try {
			
		    File sdcard = new File(Environment.getExternalStorageDirectory() + SETTING_FILE_PATH);
		    
	        if (!sdcard.exists())
	            sdcard.mkdirs();

	        File myFile = new File(sdcard, SETTING_FILE_NAME);
			FileInputStream fIn = new FileInputStream(myFile);
			BufferedReader myReader = new BufferedReader(
					new InputStreamReader(fIn));
			String aDataRow = "";
			String aBuffer = "";
			while ((aDataRow = myReader.readLine()) != null) {
				aBuffer += aDataRow + "\n";
			}
			myReader.close();
			Log.e("Read Data", aBuffer);
			
			xmlParse(aBuffer, "lastSubmissionTime", LONG_TYPE);
			xmlParse(aBuffer, "strSubmitResult", 	STRING_TYPE);
			xmlParse(aBuffer, "appID", 				STRING_TYPE);

		} catch (Exception e) {
			
		}
	}
	
	public boolean isNewInstall() {
		File sdcard = new File(Environment.getExternalStorageDirectory()
                + SETTING_FILE_PATH);
	    
        if (!sdcard.exists()) {
            return true;
        }
        
        return false;
	}
	
	public static void xmlParse(String result, String tag, int type) throws XmlPullParserException, IOException {
		
		XmlPullParser parser = Xml.newPullParser();
		
	    try {
	    	parser.setInput(new StringReader(result));
	    } catch (XmlPullParserException e) {
	    	// 	TODO Auto-generated catch block
	    	e.printStackTrace();
	    }
	        
        int eventType = parser.getEventType();
        Editor editor = sharedPreferences.edit();
        
        String xmlNodeName = null;
        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch (eventType) {
	             case XmlPullParser.START_TAG:
	                 xmlNodeName = parser.getName();
	                 break;
	             case XmlPullParser.TEXT:
	            	 if (xmlNodeName.equals(tag)) {
	            		 String value = parser.getText();
	            	   	 
	   	            	 if (type == STRING_TYPE) {
		            		 editor.putString(tag, value);
		            	 }
		            	 if (type == LONG_TYPE) {
		            		 editor.putLong(tag, Long.parseLong(value));
		            	 }
		            	 if (type == INT_TYPE) {
		            		 editor.putInt(tag, Integer.parseInt(value));
		            	 }
		            	 editor.commit();
	            	 }
	            	 break;
            }
            
            eventType = parser.next();
        }
	}
}